import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { environment } from 'environments/environment'
import { config } from '../../shared/smartadmin.config'
import { Observable } from 'rxjs/Observable'
import { NotificationService } from '../../shared/utils/notification.service'
import { timeout, catchError } from 'rxjs/operators'

@Injectable()
export class JsonApiService {
  constructor(private _http: HttpClient, private notificationService: NotificationService) {}

  public fetch(url): Observable<any> {
    return this._http
      .get(config.API_URL + url, {
        headers: new HttpHeaders({
          'X-Token': localStorage.getItem('token') || ''
        })
      })
      .delay(100)
      .map((data: any) => data.data || data)
      .catch(e => this.handleError(e))
  }
  //http2方法不带loading 开关
  public httpNotMessage(url, reqdata): Observable<any> {
    return this._http
      .post(config.BaseURL + url, reqdata, {
        headers: new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(30000))
      .map((data: any) => {
        return data
      })
      .catch(function (e) {
        let errMsg = e.message ? e.message : e.status ? `${e.status} - ${e.statusText}` : 'Server error'
        return Observable.throw(errMsg)
      })
  }
  //http2方法不带loading 开关
  public http2(url, reqdata): Observable<any> {
    return this._http
      .post(config.BaseURL + url, reqdata, {
        headers: new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(60000))
      .map((data: any) => {
        return data
      })
      .catch(e => this.handleError(e))
  }
  public http_obj(url, reqdata, loading = true): Observable<any> {
    loading && layer.load()
    let req = JSON.parse(JSON.stringify(reqdata)),
      reqStr = ''
    for (let k in req) {
      // if(req[k]){
      if (!reqStr) {
        reqStr += k + '=' + req[k]
      } else {
        reqStr += '&' + k + '=' + req[k]
      }
      // }
    }
    return this._http
      .post(config.BaseURL + url, reqStr, {
        headers: new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(60000))
      .map((data: any) => {
        loading && layer.closeAll('loading')
        return data
      })
      .catch(e => this.handleError(e))
  }
  public http(url, reqdata, loading = true): Observable<any> {
    loading && layer.load()
    return this._http
      .post(config.BaseURL + url, reqdata, {
        headers: new HttpHeaders({
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(60000))
      .map((data: any) => {
        loading && layer.closeAll('loading')
        return data
      })
      .catch(e => this.handleError(e))
  }
  public form_http(url, reqdata, loading = true): Observable<any> {
    loading && layer.load()
    return this._http
      .post(config.BaseURL + url, reqdata, {
        headers: new HttpHeaders({
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(30000))
      .map((data: any) => {
        loading && layer.closeAll('loading')
        return data
      })
      .catch(e => this.handleError(e))
  }

  public json_http(url, reqdata, loading = true): Observable<any> {
    loading && layer.load()
    return this._http
      .post(config.BaseURL + url, reqdata, {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(30000))
      .map((data: any) => {
        loading && layer.closeAll('loading')
        return data
      })
      .catch(e => this.handleError(e))
  }
  public http_get(url, loading = true): Observable<any> {
    loading && layer.load()
    return this._http
      .get(config.BaseURL + url, {
        headers: new HttpHeaders({
          'X-Token': localStorage.getItem('token') || ''
        }),
        withCredentials: true
      })
      .pipe(timeout(30000))
      .map((data: any) => {
        loading && layer.closeAll('loading')
        return data
      })
      .catch(e => this.handleError(e))
  }
  private getBaseUrl() {
    return location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/'
  }

  private handleError(error: any) {
    layer.closeAll('loading')
    if (error.name === 'TimeoutError') {
      this.notificationService.smallBox({
        content: '请求超时,请重试',
        timeout: 3000
      })
    }
    let errMsg = error.message ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'
    return Observable.throw(errMsg)
  }

  public confirm_message(message) {
    return new Promise(
      function (resolve, reject) {
        this.notificationService.smartMessageBox(
          {
            title: '提示',
            content: message,
            buttons: '[确认][取消]'
          },
          ButtonPressed => {
            if (ButtonPressed === '确认') {
              resolve()
            }
            if (ButtonPressed === '取消') {
              this.notificationService.smallBox({
                content: '操作取消',
                timeout: 3000
              })
              return
            }
          }
        )
      }.bind(this)
    )
  }

  public message(data) {
    this.notificationService.smallBox({
      content: data,
      timeout: 3000
    })
  }
}
